package xcmg.device.service.warehouse;

import com.github.pagehelper.PageInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.agent.ServiceBasicDataAgentDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaDO;
import xcmg.device.dao.entity.warehouse.WarehouseAreaLocationDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.dao.mapper.agent.ServiceBasicDataAgentMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseAreaLocationDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseDOMapper;
import xcmg.device.dao.mapper.warehouse.WarehouseInventoryMapper;
import xcmg.device.infra.BeanUtil;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.service.vo.agent.ServiceBasicDataAgentVO;
import xcmg.device.service.vo.permission.WareHousePermission;
import xcmg.device.service.vo.warehouse.AddWarehouseAreaLocationVO;
import xcmg.device.service.vo.warehouse.AddWarehouseAreaVO;
import xcmg.device.service.vo.warehouse.AddWarehouseVO;
import xcmg.device.service.vo.warehouse.InvenitoryWarehouseSearchVO;
import xcmg.device.service.vo.warehouse.InventoryCheckWarehousePreviewVO;
import xcmg.device.service.vo.warehouse.WarehouseAreaLocationVO;
import xcmg.device.service.vo.warehouse.WarehouseAreaVO;
import xcmg.device.service.vo.warehouse.WarehouseSearch;
import xcmg.device.service.vo.warehouse.WarehouseVO;
import xcmg.device.util.ServiceBasicDataAgentCodeConstantEnum;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.ListUtil;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WarehouseService {
    @Autowired
    private WarehouseDOMapper warehouseDOMapper;

    @Autowired
    private WarehouseAreaDOMapper warehouseAreaDOMapper;

    @Autowired
    private WarehouseAreaLocationDOMapper warehouseAreaLocationDOMapper;
    @Autowired
    private DepartmentWarehouseRelationService relationService;

    @Autowired
    private WarehouseInventoryMapper warehouseInventoryMapper;
    @Autowired
    private ServiceBasicDataAgentMapper serviceBasicDataAgentMapper;
    @Autowired
    private HttpServletResponse response;

    @Autowired
    private FastGenClient genClient;

    public ErrorCode addWarehouse(AddWarehouseVO addWarehouseVO, String orgId){
        int cnt = warehouseDOMapper.countByWarehouseCode(orgId, addWarehouseVO.getWarehouseCode());
        if(cnt > 0){
            return ErrorCode.WarehouseDuplicated;
        }
        int cnt2 = warehouseDOMapper.countByFactoryId(orgId, addWarehouseVO.getFactoryId(),null);
        if(cnt2 > 0){
            throw new RuntimeException("该出货地址已存在");
        }
        WarehouseDO warehouseDO = new WarehouseDO();
        warehouseDO.setId(genClient.newGuid().getValue().toString());
        warehouseDO.setWarehouseCode(addWarehouseVO.getWarehouseCode());
        warehouseDO.setOrgId(orgId);
        warehouseDO.setDescription(addWarehouseVO.getDescription());
        warehouseDO.setKeeperId(addWarehouseVO.getKeeperId());
        warehouseDO.setIsPlan(addWarehouseVO.getIsPlan());
        warehouseDO.setIsCenter(addWarehouseVO.getIsCenter());
        warehouseDO.setFirstInOut(addWarehouseVO.getFirstInOut());
        warehouseDO.setIsBarCode(addWarehouseVO.getIsBarCode() == null ? 0 : addWarehouseVO.getIsBarCode());
        warehouseDO.setWarehouseType(addWarehouseVO.getWarehouseType());
        warehouseDO.setWarehouseTypeDesc(addWarehouseVO.getWarehouseTypeDesc());
        warehouseDOMapper.insert(warehouseDO);
        return ErrorCode.Success;
    }

    public PageCommonVO getWarehouseByTypePage(SearchCommonVO<InvenitoryWarehouseSearchVO> searchVO){
        //分页设置
        PageCommonVO result = new PageCommonVO();
        PageHelperPlus.startPage(searchVO.getPageNum(), searchVO.getPageSize());
        InvenitoryWarehouseSearchVO filters = searchVO.getFilters();
        String orgId = filters.getOrgId();
        String warehouseType = filters.getWarehouseType();
        List<String> warehouseCodes = filters.getWarehouseCodes();
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.selectWarehousesByWarehouseType(orgId, warehouseType,warehouseCodes);
        List<InventoryCheckWarehousePreviewVO> warehouseVOS = new ArrayList<>();
        for(WarehouseDO warehouseDO : warehouseDOS){
            InventoryCheckWarehousePreviewVO warehouseVO = new InventoryCheckWarehousePreviewVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            warehouseVOS.add(warehouseVO);
        }
        result.setPageInfo(new PageInfo(warehouseDOS));
        result.setPageInfoList(warehouseVOS);
        return result;
    }


    /**
     * @Des 根据仓库类型查询仓库列表
     * @Date 2020/11/3 19:22
     * @Author wangzhaoyu
     * @Param [warehouseType]
     * @Return java.util.List<xcmg.device.service.vo.warehouse.WarehouseVO>
     */
    public List<WarehouseVO> getWarehouseByWarehouseType(String orgId,String warehouseType){
        if(StringUtils.isEmpty(warehouseType)){
            return Collections.EMPTY_LIST;
        }
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.selectWarehousesByWarehouseType(orgId, warehouseType,null);
        List<WarehouseVO> result = new ArrayList<>();
        for(WarehouseDO warehouseDO : warehouseDOS){
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            result.add(warehouseVO);
        }
        return result;
    }

    public ErrorCode addArea(AddWarehouseAreaVO addWarehouseArea){
        int count = warehouseAreaDOMapper.countByWarehouseAreaId(addWarehouseArea.getWarehouseId(), addWarehouseArea.getAreaCode());
        if(count > 0){
            return ErrorCode.WarehouseAreaDuplicated;
        }
        WarehouseAreaDO warehouseAreaDO = new WarehouseAreaDO();
        warehouseAreaDO.setId(genClient.newGuid().getValue().toString());
        warehouseAreaDO.setAreaCode(addWarehouseArea.getAreaCode());
        warehouseAreaDO.setWarehouseId(addWarehouseArea.getWarehouseId());
        warehouseAreaDO.setAttrId(addWarehouseArea.getAttrId());
        warehouseAreaDO.setAttrDesc(addWarehouseArea.getAttrDesc());
        warehouseAreaDO.setDescription(addWarehouseArea.getDescription());
        warehouseAreaDO.setSapCode(addWarehouseArea.getSapCode());
        warehouseAreaDO.setOrgId(addWarehouseArea.getOrgId());
        warehouseAreaDOMapper.insert(warehouseAreaDO);
        return ErrorCode.Success;
    }

    /**
     * @Des 停用或启用库区
     * @Date 2020/10/27 13:58
     * @Author wangzhaoyu
     * @Param []
     * @Return void
     */
    public ErrorCode areaOpenOrStopUsing(String areaId, Integer stopUsing) {
        int i = warehouseAreaDOMapper.updateStopUsing(areaId, stopUsing);
        if (i <= 0) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    /**
     * @Des 停用或启用库区
     * @Date 2020/10/27 13:58
     * @Author wangzhaoyu
     * @Param []
     * @Return void
     */
    public ErrorCode warehouseOpenOrStopUsing(String areaId, Integer stopUsing) {
        int i = warehouseDOMapper.updateStopUsing(areaId, stopUsing);
        if (i <= 0) {
            return ErrorCode.Failure;
        }
        return ErrorCode.Success;
    }

    /**
     * 添加储位信息
     *
     * @param warehouseAreaLocationVO AddWarehouseAreaLocationVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode addWarehouseAreaLocations(AddWarehouseAreaLocationVO warehouseAreaLocationVO) {
        int beginRowNo = warehouseAreaLocationVO.getBeginRowNo().intValue();
        int endRowNo = warehouseAreaLocationVO.getEndRowNo().intValue();
        int floorNum = warehouseAreaLocationVO.getFloorNum();
        int columnNum = warehouseAreaLocationVO.getColumnNum();
        int locationNum = warehouseAreaLocationVO.getLocationNum();
        List<WarehouseAreaLocationDO> warehouseAreaLocationDOList = new ArrayList<>();
        for (int rowNo = beginRowNo; rowNo <= endRowNo; ++rowNo)
        {
            for (int floorNo = 1; floorNo <= floorNum; ++floorNo)
            {
                for (int columnNo = 1; columnNo <= columnNum; ++columnNo)
                {
                    for (int locationNo = 1; locationNo <= locationNum; ++locationNo)
                    {
                        WarehouseAreaLocationDO locationDO = genWarehouseAreaLocationDO(warehouseAreaLocationVO.getShelfType(), warehouseAreaLocationVO.getWarehouseCode(), warehouseAreaLocationVO.getWarehouseAreaId(), rowNo, floorNo, columnNo, locationNo, warehouseAreaLocationVO.getShelfNo(),warehouseAreaLocationVO.getAreaNo(),warehouseAreaLocationVO.getOrgId());
                        warehouseAreaLocationDOList.add(locationDO);
                    }
                }
            }
        }
        if (ListUtil.isNullOrEmpty(warehouseAreaLocationDOList))
        {
            return ErrorCode.Success;
        }

        List<List<WarehouseAreaLocationDO>> listList = this.subList(warehouseAreaLocationDOList);
        if (null != listList && !listList.isEmpty()){
            for (List<WarehouseAreaLocationDO> list: listList) {
                warehouseAreaLocationDOMapper.batchUpdateInsert(list);
            }
        }
        return ErrorCode.Success;
    }


    /**
     * 删除储位信息
     * @param warehouseAreaLocationVO AddWarehouseAreaLocationVO
     * @return ErrorCode
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode delWarehouseAreaLocations(AddWarehouseAreaLocationVO warehouseAreaLocationVO)
    {
        //校验货架是否存在
        String shelfNo = warehouseAreaLocationVO.getShelfNo();
        String warehouseAreaId = warehouseAreaLocationVO.getWarehouseAreaId();
        int count = warehouseAreaLocationDOMapper.countByShelfNo(warehouseAreaId, shelfNo);
        if (count <= 0){
            return ErrorCode.ShelfInfoDoesNotExist;
        }
        if (!isAllowDelLocation(warehouseAreaLocationVO)) {
            return ErrorCode.LocationExistsStockNotAllowDel;
        }

        return warehouseAreaLocationDOMapper.deleteByShelfNo(warehouseAreaId,shelfNo) > 0 ?ErrorCode.Success:ErrorCode.Failure;
    }

    /**
     * 校验是否允许新增储位
     *
     * @param warehouseAreaLocationVO
     * @return
     */
    private Boolean isAllowDelLocation(AddWarehouseAreaLocationVO warehouseAreaLocationVO) {
        String locationCodePre = warehouseAreaLocationVO.getShelfNo() + "-";
        //判断该储位是否在零件如不存在，允许清除
        BigDecimal locationStocks = warehouseInventoryMapper
                .countByLocationCode(warehouseAreaLocationVO.getWarehouseCode(), warehouseAreaLocationVO.getAreaNo(), locationCodePre, warehouseAreaLocationVO.getOrgId());
        if (null == locationStocks || locationStocks.compareTo(BigDecimal.ZERO) <= 0) {
            return true;
        }

        return false;
    }

    /**
     * 按指定大小，分隔集合，将集合按规定个数分为n个部分
     *  @param list 参数
     *
     */
    private List<List<WarehouseAreaLocationDO>> subList(List<WarehouseAreaLocationDO> list) {
        if (list == null || list.size() == 0 ) {
            return null;
        }
        List<List<WarehouseAreaLocationDO>> result = new ArrayList<>();
        int size = list.size();
        int count = (size + 500 - 1) / 500;
        for (int i = 0; i < count; i++) {
            List<WarehouseAreaLocationDO> subList = list.subList(i * 500, ((i + 1) * 500 > size ? size : 500 * (i + 1)));
            result.add(subList);
        }
        return result;
    }

    public void exportWarehouses(String warehouseCode, String description, String orgId,String keyWords,String billNos,String purchaseOrgName,String warehouseType) throws Exception {
        if(StringUtils.isEmpty(orgId)){
            return;
        }

        List<String> warehouseCodeList = new ArrayList<>();
        if (!StringUtil.isNullOrEmpty(billNos)){
            warehouseCodeList = Arrays.asList(billNos.split(","));
        }
        PageHelperPlus.orderBy("ID");
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.list(warehouseCode, description, orgId,keyWords,warehouseCodeList,purchaseOrgName,warehouseType, null);
        if(CollectionUtils.isEmpty(warehouseDOS)){
            return;
        }
        warehousesExportInvoke(warehouseDOS,orgId);
    }

    private void warehousesExportInvoke(List<WarehouseDO> warehouseDOS,String orgId) throws Exception {
        //从字典表中获取仓库类型的定义，用于显示仓库类型描述
        Map<String, ServiceBasicDataAgentDO> serviceBasicDataAgentDOMap = warehouseTypeMap(orgId);
        String title = "仓库数据导出";
        String[] rowsName = new String[]{"序号", "仓库编号", "仓库描述", "是否计划仓库", "是否中心仓库", "是否先入先出",
                "是否条码化", "仓库类型编码", "仓库类型"};
        Object[] objs = null;
        List<Object[]> dataList = new ArrayList<Object[]>();
        for(int i = 0 ; i< warehouseDOS.size();i++){
            WarehouseDO warehouse = warehouseDOS.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = warehouse.getWarehouseCode();
            objs[2] = warehouse.getDescription();
            Integer isPlan = warehouse.getIsPlan();
            String isPlanStr =  (isPlan != null && isPlan.compareTo(1) == 0) ? "是" : "否";
            objs[3] = isPlanStr;
            Integer isCenter = warehouse.getIsCenter();
            String isCenterStr = (isCenter != null && isCenter.compareTo(1) == 0) ? "是" : "否";
            objs[4] = isCenterStr;
            Integer firstInOut = warehouse.getFirstInOut();
            String firstInOutStr = (firstInOut != null && firstInOut.compareTo(1) == 0) ? "是" : "否";
            objs[5] = firstInOutStr;
            Integer isBarCode = warehouse.getIsBarCode();
            String isBarCodeStr = (isBarCode != null && isBarCode.compareTo(1) == 0) ? "是" : "否";
            objs[6] = isBarCodeStr;
            String warehouseType = warehouse.getWarehouseType();
            objs[7] = warehouseType;
            String warehouseTypeDesc = warehouse.getWarehouseTypeDesc();
            ServiceBasicDataAgentDO basicDataAgent = serviceBasicDataAgentDOMap.get(warehouseType);
            if(basicDataAgent != null){
                warehouseTypeDesc = basicDataAgent.getName();
            }
            objs[8] = warehouseTypeDesc;
            dataList.add(objs);
        }
        ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
        exportUtil.export(response);
    }
    public PageCommonVO<WarehouseVO> listWarehouses2(int pageNum, int pageSize,  WarehouseSearch param) {
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.queryList(param);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = BeanUtil.do2bo(warehouseDO, WarehouseVO.class);
            warehouseVOS.add(warehouseVO);
        }
        PageCommonVO<WarehouseVO> pageCommonVO =new PageCommonVO<>();
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    @Deprecated
    public PageCommonVO<WarehouseVO> listWarehouses(int pageNum, int pageSize, String warehouseCode, String description, String orgId,
                                       String keyWords,String billNos,String purchaseOrgName,String warehouseType, Integer stopUsing) {
        if (orgId == null || orgId.isEmpty()) {
            return new PageCommonVO();
        }

        List<String> warehouseCodeList = new ArrayList<>();
        if (!StringUtil.isNullOrEmpty(billNos)) {
            warehouseCodeList = Arrays.asList(billNos.split(","));
        }
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.list(warehouseCode, description, orgId, keyWords, warehouseCodeList, purchaseOrgName, warehouseType, stopUsing);
        //从字典表中获取仓库类型的定义，用于显示仓库类型描述
        Map<String, ServiceBasicDataAgentDO> serviceBasicDataAgentDOMap = warehouseTypeMap(orgId);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            ServiceBasicDataAgentDO basicDataAgent = serviceBasicDataAgentDOMap.get(warehouseDO.getWarehouseType());
            if (basicDataAgent != null) {
                warehouseVO.setWarehouseTypeDesc(basicDataAgent.getName());
            }
            warehouseVOS.add(warehouseVO);
        }
        PageCommonVO pageCommonVO =new PageCommonVO<WarehouseVO>();
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    private Map<String,ServiceBasicDataAgentDO> warehouseTypeMap(String orgId){
        String warehouseTypeCOde = ServiceBasicDataAgentCodeConstantEnum.WAREHOUSE_TYPE_CODE.code;
        ServiceBasicDataAgentVO queryAgentParam = new ServiceBasicDataAgentVO();
        queryAgentParam.setOrgId(orgId);
        queryAgentParam.setpCode(warehouseTypeCOde);
        List<ServiceBasicDataAgentDO> serviceBasicDataAgentDOS = serviceBasicDataAgentMapper.queryList(queryAgentParam);
        if(CollectionUtils.isEmpty(serviceBasicDataAgentDOS)){
            return Collections.EMPTY_MAP;
        }
        Map<String,ServiceBasicDataAgentDO> result = new HashMap<>();
        for(ServiceBasicDataAgentDO basicDataAgent : serviceBasicDataAgentDOS){
            result.put(basicDataAgent.getCode(),basicDataAgent);
        }
        return result;
    }



    /**
     * @Des 带权限过滤的仓库查询（主库区）
     * @Date 2020/10/22 14:23
     * @Author wangzhaoyu
     * @Param [pageNum, pageSize, warehouseCode, description, orgId, departmentId]
     * @Return yb.ecp.fast.infra.infra.PageCommonVO
     */
    public PageCommonVO listWarehousesMajorPermit(int pageNum, int pageSize, String warehouseCode, String description, String orgId,String departmentId, Integer stopUsing) {
        if(orgId==null||orgId.isEmpty()) {
            return new PageCommonVO();
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        WareHousePermission wareHousePermission = relationService.hasMajorWareHousePermission(orgId, departmentId);
        if (!wareHousePermission.isHasPermission()) {
            pageCommonVO.setPageInfo(new PageInfo(Collections.EMPTY_LIST));
            pageCommonVO.setPageInfoList(Collections.EMPTY_LIST);
            return pageCommonVO;
        }
        List<String> permissionWarehouses = wareHousePermission.getPermissionWarehouses();
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.listPermit(warehouseCode, description, orgId, permissionWarehouses, stopUsing);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            warehouseVOS.add(warehouseVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    /**
     * @Des 根据仓库库存权限配置返回可以查看到的仓库、
     * @Date 2020/12/17 14:59
     * @Author wangzhaoyu
     * @Param [pageNum, pageSize, warehouseCode, description, orgId, departmentId]
     * @Return yb.ecp.fast.infra.infra.PageCommonVO
     */
    public PageCommonVO listInventoryPermit(int pageNum, int pageSize, String warehouseCode, String description, String orgId,String departmentId){
        if(orgId==null||orgId.isEmpty()) {
            return new PageCommonVO();
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        WareHousePermission wareHousePermission = relationService.hasWarehouseInveryControPermisson(orgId, departmentId);
        if (!wareHousePermission.isHasPermission()) {
            pageCommonVO.setPageInfo(new PageInfo(Collections.EMPTY_LIST));
            pageCommonVO.setPageInfoList(Collections.EMPTY_LIST);
            return pageCommonVO;
        }
        List<String> permissionWarehouses = wareHousePermission.getPermissionWarehouses();
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.listPermit(warehouseCode, description, orgId, permissionWarehouses, null);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            warehouseVOS.add(warehouseVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    /**
    *@Description 带权限过滤的仓库查询（主库区+次库区）
    *@Author wzy
    *@Date 2020/8/29
    *@Time 18:07
    */
    public PageCommonVO listWarehousesPermit(int pageNum, int pageSize, String warehouseCode, String description, String orgId,String departmentId, Integer stopUsing) {
        if(orgId==null||orgId.isEmpty()) {
            return new PageCommonVO();
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        WareHousePermission wareHousePermission = relationService.wareHouseChoicePermit(orgId, departmentId);
        if (!wareHousePermission.isHasPermission()) {
            pageCommonVO.setPageInfo(new PageInfo(Collections.EMPTY_LIST));
            pageCommonVO.setPageInfoList(Collections.EMPTY_LIST);
            return pageCommonVO;
        }
        List<String> permissionWarehouses = wareHousePermission.getPermissionWarehouses();
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.listPermit(warehouseCode, description, orgId, permissionWarehouses, stopUsing);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            warehouseVOS.add(warehouseVO);
        }
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    public PageCommonVO listNoBarcode(int pageNum, int pageSize, String orgId, String warehouseCode, String description) {
        if (orgId == null || orgId.isEmpty()) {
            return new PageCommonVO();
        }

        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseDO> warehouseDOS = warehouseDOMapper.listNoBarcode(orgId, warehouseCode, description);
        List<WarehouseVO> warehouseVOS = new ArrayList<>();
        for (WarehouseDO warehouseDO : warehouseDOS) {
            WarehouseVO warehouseVO = new WarehouseVO();
            BeanUtils.copyProperties(warehouseDO, warehouseVO);
            warehouseVOS.add(warehouseVO);
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        pageCommonVO.setPageInfo(new PageInfo(warehouseDOS));
        pageCommonVO.setPageInfoList(warehouseVOS);
        return pageCommonVO;
    }

    public PageCommonVO listAreas(int pageNum, int pageSize, String warehouseId) {
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseAreaDO> warehouseAreaDOS = warehouseAreaDOMapper.list(warehouseId);
        List<WarehouseAreaVO> warehouseAreaVOS = new ArrayList<>();
        for (WarehouseAreaDO warehouseAreaDO : warehouseAreaDOS) {
            WarehouseAreaVO warehouseAreaVO = new WarehouseAreaVO();
            BeanUtils.copyProperties(warehouseAreaDO, warehouseAreaVO);
            warehouseAreaVOS.add(warehouseAreaVO);
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        pageCommonVO.setPageInfo(new PageInfo(warehouseAreaDOS));
        pageCommonVO.setPageInfoList(warehouseAreaVOS);
        return pageCommonVO;
    }

    public List<WarehouseAreaVO> moreAreaList(String warehouseIds) {
        List<String> warehouseIdList=new ArrayList<>();
        if(!StringUtils.isEmpty(warehouseIds)){
            String[] str = warehouseIds.trim().replace("，", ",").split(",");
            warehouseIdList=(Arrays.asList((str)));
        }else {
            return new ArrayList<>();
        }

        List<WarehouseAreaDO> warehouseAreaDOS = warehouseAreaDOMapper.moreAreaList(warehouseIdList);
        List<WarehouseAreaVO> warehouseAreaVOS = new ArrayList<>();
        for(WarehouseAreaDO warehouseAreaDO: warehouseAreaDOS){
            WarehouseAreaVO warehouseAreaVO = new WarehouseAreaVO();
            BeanUtils.copyProperties(warehouseAreaDO, warehouseAreaVO);
            warehouseAreaVOS.add(warehouseAreaVO);
        }
        return warehouseAreaVOS;
    }

    public PageCommonVO listLocations(int pageNum, int pageSize, String areaId) {
        PageHelperPlus.orderBy("LOCATION_CODE");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseAreaLocationDO> locationDOS = warehouseAreaLocationDOMapper.list(areaId);
        List<WarehouseAreaLocationVO> locationVOS = new ArrayList<>();
        for (WarehouseAreaLocationDO locationDO : locationDOS) {
            WarehouseAreaLocationVO locationVO = new WarehouseAreaLocationVO();
            BeanUtils.copyProperties(locationDO, locationVO);
            locationVOS.add(locationVO);
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        pageCommonVO.setPageInfo(new PageInfo(locationDOS));
        pageCommonVO.setPageInfoList(locationVOS);
        return pageCommonVO;
    }

    public PageCommonVO listShlefNos(int pageNum, int pageSize, String areaId) {
        PageHelperPlus.orderBy("SHELF_NO");
        PageHelperPlus.startPage(pageNum, pageSize);
        List<WarehouseAreaLocationDO> locationDOS = warehouseAreaLocationDOMapper.findShelfNoByAreaId(areaId);
        List<WarehouseAreaLocationVO> locationVOS = new ArrayList<>();
        for (WarehouseAreaLocationDO locationDO : locationDOS) {
            WarehouseAreaLocationVO locationVO = new WarehouseAreaLocationVO();
            BeanUtils.copyProperties(locationDO, locationVO);
            locationVOS.add(locationVO);
        }
        PageCommonVO pageCommonVO = new PageCommonVO();
        pageCommonVO.setPageInfo(new PageInfo(locationDOS));
        pageCommonVO.setPageInfoList(locationVOS);
        return pageCommonVO;
    }

    public ErrorCode deleteWarehouse(String warehouseId){
        warehouseDOMapper.deleteByPrimaryKey(warehouseId);
        return ErrorCode.Success;
    }

    public ErrorCode deleteArea(String warehouseAreaId){
        warehouseAreaLocationDOMapper.deleteByAreaId(warehouseAreaId);
        warehouseAreaDOMapper.deleteByAreaId(warehouseAreaId);
        return ErrorCode.Success;
    }

    private void deleteLocationsByRowNoRange(AddWarehouseAreaLocationVO areaLocationVO){
        warehouseAreaLocationDOMapper.deleteByRowNoRange(areaLocationVO);
    }

    private WarehouseAreaLocationDO genWarehouseAreaLocationDO(String shelfType, String warehouseCode, String warehouseAreaId,
                                                               int rowNo, int floorNo, int columnNo, int locationNo,String shelfNo,String areaCode,String orgId){
        StringBuffer sb = new StringBuffer();
        sb.append(shelfNo)
                .append("-")
                .append(rowNo)
                .append("-")
                .append(floorNo)
                .append("-")
                .append(columnNo)
                .append("-")
                .append(locationNo)
                .append("-")
                .append(areaCode)
                .append("-")
                .append(warehouseCode);
        WarehouseAreaLocationDO locationDO = new WarehouseAreaLocationDO();
        locationDO.setLocationCode(sb.toString());
        locationDO.setWarehouseAreaId(warehouseAreaId);
        locationDO.setRowNo(String.valueOf(rowNo));
        locationDO.setFloorNo(String.valueOf(floorNo));
        locationDO.setColumnNo(String.valueOf(columnNo));
        locationDO.setSeqNo(String.valueOf(locationNo));
        locationDO.setShelfType(shelfType);
        locationDO.setShelfNo(shelfNo);
        locationDO.setOrgId(orgId);
        String locationDesc=locationDO.getShelfType().concat(locationDO.getRowNo()).concat("排").concat(locationDO.getFloorNo()).concat("层").concat(locationDO.getColumnNo()).concat("列").concat(locationDO.getSeqNo()).concat("位");
        locationDO.setLocationDesc(locationDesc);
        locationDO.setCreateTime(new Date());
        return locationDO;
    }

    public PageCommonVO findAreaCodeList(String warehouseCode, String orgId){
        PageCommonVO pageCommonVO =new PageCommonVO();
        WarehouseDO warehouseDO = warehouseDOMapper.itemByWarehouseCode(orgId, warehouseCode);
        if(warehouseDO == null){
            return pageCommonVO;
        }
        pageCommonVO.setPageInfo(new PageInfo(warehouseAreaDOMapper.list(warehouseDO.getId())));
        return pageCommonVO;
    }
    
    public PageCommonVO findAbleAreaCodeList(String warehouseCode, String orgId) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        WarehouseDO warehouseDO = warehouseDOMapper.itemByWarehouseCode(orgId, warehouseCode);
        if (warehouseDO == null) {
            return pageCommonVO;
        }
        pageCommonVO.setPageInfo(new PageInfo(warehouseAreaDOMapper.listAbleInfos(warehouseDO.getId())));
        return pageCommonVO;
    }

    public PageCommonVO areaCodeListPage(int pageNum, int pageSize,String warehouseCode, String orgId, Integer stopUsingControl) {
        PageCommonVO pageCommonVO = new PageCommonVO();
        WarehouseDO warehouseDO = warehouseDOMapper.itemByWarehouseCode(orgId, warehouseCode);
        if (warehouseDO == null) {
            return pageCommonVO;
        }
        PageHelperPlus.orderBy("ID");
        PageHelperPlus.startPage(pageNum, pageSize);
        //List<WarehouseAreaDO> areaDOS = warehouseAreaDOMapper.list(warehouseDO.getId());
        List<WarehouseAreaDO> areaDOS = warehouseAreaDOMapper.listStopUsingControl(warehouseDO.getId(), stopUsingControl);
        List<WarehouseAreaVO> areaVOS = new ArrayList<>();
        for (WarehouseAreaDO areaDO : areaDOS) {
            WarehouseAreaVO areaVO = new WarehouseAreaVO();
            BeanUtils.copyProperties(areaDO, areaVO);
            areaVOS.add(areaVO);
        }

        pageCommonVO.setPageInfo(new PageInfo(areaDOS));
        pageCommonVO.setPageInfoList(areaVOS);
        return pageCommonVO;
    }

    public ErrorCode updateLocationDesc(WarehouseAreaLocationVO warehouseAreaLocationVO){
        if(StringUtil.isNullOrEmpty(warehouseAreaLocationVO.getLocationCode())||StringUtil.isNullOrEmpty(warehouseAreaLocationVO.getWarehouseAreaId())){
            return ErrorCode.AbnormalDetailArgumentError;
        }
        return warehouseAreaLocationDOMapper.updateLocationDesc(warehouseAreaLocationVO)>0?ErrorCode.Success:ErrorCode.Failure;
    }

    public void update(WarehouseVO warehouseVO) throws Exception {
        if (warehouseDOMapper.countNotSelfByDesc(warehouseVO.getOrgId(), StringUtils.trim(warehouseVO.getDescription()),warehouseVO.getId()) > 0) {
            throw new Exception("该仓库名已存在");
        }
        int cnt2 = warehouseDOMapper.countByFactoryId(warehouseVO.getOrgId(), warehouseVO.getFactoryId(),warehouseVO.getId());
        if(cnt2 > 0){
            throw new RuntimeException("该出货地址已存在");
        }
        WarehouseDO warehouseDO = new WarehouseDO();
        BeanUtils.copyProperties(warehouseVO, warehouseDO);
        warehouseDOMapper.updateByPrimaryKeySelective(warehouseDO);
    }

    public int countIsBarCode(String orgId,String warehouseCode){
        int countIsBarCode = warehouseDOMapper.countIsBarCode(orgId, warehouseCode);
        return countIsBarCode;
    }

    public WarehouseDO queryByFactoryId(String factoryid, String orgId) {
        WarehouseSearch param = new WarehouseSearch();
        param.setOrgId(orgId);
        param.setFactoryId(factoryid);
        param.setStopUsing(0);
        List<WarehouseDO> l = warehouseDOMapper.queryList(param);
        return l.size() > 0 ? l.get(0) : null;
    }
}
